# 自定义Admin视图 - 完全重构，使用前台相同的数据获取方式
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import user_passes_test
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
import json

from .models import Product, Comment, Rate, Tags, User as ProductUser, UserTagPrefer, LikeComment


def is_admin_user(user):
    """检查用户是否是管理员"""
    return user.is_authenticated and user.is_staff and user.is_superuser


@user_passes_test(is_admin_user)
def custom_admin_dashboard(request):
    """自定义管理仪表板 - 使用前台相同的数据获取方式"""
    
    # 获取操作历史记录
    from django.contrib.admin.models import LogEntry
    from django.db.models import Count
    
    # 最近的操作记录
    recent_logs = LogEntry.objects.select_related('user', 'content_type').order_by('-action_time')[:10]
    
    # 用户操作统计
    user_stats = LogEntry.objects.values('user__username').annotate(
        count=Count('id')
    ).order_by('-count')[:5]
    
    # 操作类型统计
    action_names = {1: '新增', 2: '修改', 3: '删除'}
    action_stats = []
    for flag in [1, 2, 3]:
        count = LogEntry.objects.filter(action_flag=flag).count()
        action_stats.append({
            'name': action_names[flag],
            'count': count,
            'flag': flag
        })
    
    context = {
        'title': '跨境电商产品推荐与展示系统 - 管理后台',
        'product_count': Product.objects.count(),
        'comment_count': Comment.objects.count(),
        'rate_count': Rate.objects.count(),
        'tag_count': Tags.objects.count(),
        'user_count': ProductUser.objects.count(),
        'recent_logs': recent_logs,
        'user_stats': user_stats,
        'action_stats': action_stats,
        'total_logs': LogEntry.objects.count(),
    }
    return render(request, 'custom_admin/dashboard.html', context)


@user_passes_test(is_admin_user)
def custom_admin_products(request):
    """产品管理 - 使用前台完全相同的数据获取方式"""
    
    # 使用和前台index视图完全相同的方式获取数据
    order = request.GET.get('order', 'price')
    search = request.GET.get('search', '')
    
    if order == 'collect':
        from django.db.models import Count
        products = Product.objects.annotate(collectors=Count('collect')).order_by('-collectors')
        title = '收藏排序'
    elif order == 'rate':
        from django.db.models import Avg
        products = Product.objects.all().annotate(marks=Avg('rate__mark')).order_by('-marks')
        title = '评分排序'
    else:
        # 默认按价格排序 - 和前台完全一致
        products = Product.objects.order_by('-price')
        title = '价格排序'
    
    # 搜索功能 - 和前台完全一致
    if search:
        products = products.filter(
            Q(name__icontains=search) | Q(shop_name__icontains=search)
        )
        title = f'搜索结果: {search}'
    
    # 分页 - 和前台完全一致
    paginator = Paginator(products, 20)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    context = {
        'title': title,
        'page_obj': page_obj,
        'products': page_obj,
        'search': search,
        'order': order,
        'total_count': products.count(),
    }
    return render(request, 'custom_admin/products.html', context)


@user_passes_test(is_admin_user)
def custom_admin_comments(request):
    """评论管理 - 使用前台相同的数据获取方式"""
    
    # 使用简单的查询方式
    comments = Comment.objects.order_by('-create_time')
    
    # 搜索功能
    search = request.GET.get('search', '')
    if search:
        comments = comments.filter(Q(content__icontains=search))
    
    # 分页
    paginator = Paginator(comments, 20)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    context = {
        'title': '评论管理',
        'page_obj': page_obj,
        'comments': page_obj,
        'search': search,
        'total_count': comments.count(),
    }
    return render(request, 'custom_admin/comments.html', context)


@user_passes_test(is_admin_user)
def custom_admin_rates(request):
    """评分管理 - 使用前台相同的数据获取方式"""
    
    # 使用简单的查询方式
    rates = Rate.objects.order_by('-create_time')
    
    # 分页
    paginator = Paginator(rates, 20)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    context = {
        'title': '评分管理',
        'page_obj': page_obj,
        'rates': page_obj,
        'total_count': rates.count(),
    }
    return render(request, 'custom_admin/rates.html', context)


@user_passes_test(is_admin_user)
def custom_admin_tags(request):
    """标签管理 - 使用前台相同的数据获取方式"""
    
    # 使用简单的查询方式
    tags = Tags.objects.order_by('name')
    
    # 搜索功能
    search = request.GET.get('search', '')
    if search:
        tags = tags.filter(Q(name__icontains=search))
    
    # 分页
    paginator = Paginator(tags, 20)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    context = {
        'title': '标签管理',
        'page_obj': page_obj,
        'tags': page_obj,
        'search': search,
        'total_count': tags.count(),
    }
    return render(request, 'custom_admin/tags.html', context)


@user_passes_test(is_admin_user)
def custom_admin_users(request):
    """用户管理 - 使用前台相同的数据获取方式"""
    
    # 使用简单的查询方式
    users = ProductUser.objects.order_by('-created_time')
    
    # 搜索功能
    search = request.GET.get('search', '')
    if search:
        users = users.filter(
            Q(username__icontains=search) | Q(email__icontains=search)
        )
    
    # 分页
    paginator = Paginator(users, 20)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    context = {
        'title': '用户管理',
        'page_obj': page_obj,
        'users': page_obj,
        'search': search,
        'total_count': users.count(),
    }
    return render(request, 'custom_admin/users.html', context)


@user_passes_test(is_admin_user)
def custom_admin_product_detail(request, product_id):
    """产品详情 - 使用前台相同的数据获取方式"""
    
    # 使用和前台product视图完全相同的方式
    product = get_object_or_404(Product, pk=product_id)
    comments = product.comment_set.order_by("-create_time")
    
    from django.db.models import Avg
    product_rate = Rate.objects.filter(product=product).aggregate(Avg('mark'))
    if product_rate:
        product_rate = product_rate['mark__avg']
    else:
        product_rate = 0
    
    context = {
        'title': f'产品详情 - {product.name}',
        'product': product,
        'comments': comments,
        'product_rate': product_rate,
    }
    return render(request, 'custom_admin/product_detail.html', context)


# AJAX API 视图
@csrf_exempt
@user_passes_test(is_admin_user)
def custom_admin_api_delete_product(request, product_id):
    """删除产品 API"""
    if request.method == 'POST':
        try:
            product = get_object_or_404(Product, pk=product_id)
            product_name = product.name
            product.delete()
            return JsonResponse({
                'success': True, 
                'message': f'产品 "{product_name}" 删除成功'
            })
        except Exception as e:
            return JsonResponse({
                'success': False, 
                'message': f'删除失败: {str(e)}'
            })
    return JsonResponse({'success': False, 'message': '无效请求'})


@csrf_exempt
@user_passes_test(is_admin_user)
def custom_admin_api_delete_comment(request, comment_id):
    """删除评论 API"""
    if request.method == 'POST':
        try:
            comment = get_object_or_404(Comment, pk=comment_id)
            comment.delete()
            return JsonResponse({
                'success': True, 
                'message': '评论删除成功'
            })
        except Exception as e:
            return JsonResponse({
                'success': False, 
                'message': f'删除失败: {str(e)}'
            })
    return JsonResponse({'success': False, 'message': '无效请求'})